package cn.com.easy.utils;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

/**
 * 图片水印处理
 * 
 * @author nibili 2016年12月29日
 * 
 */
public class ImageUtils {

	public static void main(String[] args) {
		String srcImgPath = "E:/home/project/qmyx-web-front/root/haibao/bzw.jpg";
		String qrPath = "E:/home/project/qmyx-web-front/root/grcode/oLP4Qv80vFMnGUVqvTUwQC1BATmI.jpg";
		String targerPath = "E:/home/project/qmyx-web-front/root/haibao/oLP4Qv80vFMnGUVqvTUwQC1BATmI.jpg";
		// 给图片添加二维码水印
		ImageUtils.markImageByIcon(qrPath, srcImgPath, targerPath, 251, 1746, 320, 320);
		// 给图片添加头像

		String headPathDir = "E:/home/project/qmyx-web-front/root/head";
		String headPath = headPathDir + "/oLP4Qv80vFMnGUVqvTUwQC1BATmI.jpg";
		if (new File(headPathDir).exists() == false) {
			new File(headPathDir).mkdirs();
		}
		try {
			writeFileToDisk("http://wx.qlogo.cn/mmopen/eQcZzvo2o7smJia67rWJ5yoLlccUTPjZl581qibnjWoMmnaiadOfflLGvUic4HF0qrKqNpiaUicHPqzUoavyfmzfoqcBOgNXr63ibla/0", headPath);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		ImageUtils.markImageByIcon(headPath, targerPath, targerPath, 539, 743, 160, 160);

		// 给图片添加文字
		ImageUtils.markText(targerPath, targerPath, "古月", 42, 0, 927);
	}

	/**
	 * 给图片添加水印
	 * 
	 * @param iconPath
	 *            水印图片路径
	 * @param srcImgPath
	 *            源图片路径
	 * @param targerPath
	 *            目标图片路径
	 */
	public static void markImageByIcon(String iconPath, String srcImgPath, String targerPath, int x, int y, int width, int height) {
		markImageByIcon(iconPath, srcImgPath, targerPath, null, x, y, width, height);
	}

	/**
	 * 给图片添加水印、可设置水印图片旋转角度
	 * 
	 * @param iconPath
	 *            水印图片路径
	 * @param srcImgPath
	 *            源图片路径
	 * @param targerPath
	 *            目标图片路径
	 * @param degree
	 *            水印图片旋转角度
	 */
	public static void markImageByIcon(String iconPath, String srcImgPath, String targerPath, Integer degree, int x, int y, int width, int height) {
		OutputStream os = null;
		try {
			Image srcImg = ImageIO.read(new File(srcImgPath));

			BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null), srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB);

			// 得到画笔对象
			// Graphics g= buffImg.getGraphics();
			Graphics2D g = buffImg.createGraphics();

			// 设置对线段的锯齿状边缘处理
			g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);

			g.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null), srcImg.getHeight(null), Image.SCALE_SMOOTH), 0, 0, null);

			if (null != degree) {
				// 设置水印旋转
				g.rotate(Math.toRadians(degree), (double) buffImg.getWidth() / 2, (double) buffImg.getHeight() / 2);
			}

			// 水印图象的路径 水印一般为gif或者png的，这样可设置透明度
			ImageIcon imgIcon = new ImageIcon(iconPath);

			// 得到Image对象。
			Image img = imgIcon.getImage();

			float alpha = 1f; // 透明度
			g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));

			// 表示水印图片的位置
			// 215, 450, 290, 270
			g.drawImage(img, x, y, width, height, null); // 位置、位置、大小、大小

			g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));

			g.dispose();

			os = new FileOutputStream(targerPath);

			// 生成图片
			ImageIO.write(buffImg, "JPG", os);

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != os)
					os.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 添加文字水印
	 * 
	 * @param srcImgPath
	 *            原图片
	 * @param outImgPath
	 *            目标位置
	 * @param markContentColor
	 * @param waterMarkContent
	 * @param fontHeight
	 * @param fromX
	 * @author lvzf 2016年11月10日
	 */
	public static void markText(String srcImgPath, String outImgPath, String waterMarkContent, int fontHeight, int fromX, int fromY) {
		try {
			// 读取原图片信息
			File srcImgFile = new File(srcImgPath);
			Image srcImg = ImageIO.read(srcImgFile);
			int srcImgWidth = srcImg.getWidth(null);
			int srcImgHeight = srcImg.getHeight(null);
			// 加水印
			BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
			Graphics2D g = bufImg.createGraphics();
			g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
			// Font font = new Font("Courier New", Font.PLAIN, 12);
			Font font = new Font("宋体", Font.PLAIN, fontHeight);
			g.setColor(Color.BLACK); // 根据图片的背景设置水印颜色

			g.setFont(font);
			int x = fromX;
			if (x == 0) {
				x = srcImgWidth / 2 - getWatermarkLength(waterMarkContent, g) / 2;
			}
			int y = fontHeight + fromY;
			// int x = (srcImgWidth - getWatermarkLength(watermarkStr, g)) / 2;
			// int y = srcImgHeight / 2;
			g.drawString(waterMarkContent, x, y);
			g.dispose();
			// 输出图片
			FileOutputStream outImgStream = new FileOutputStream(outImgPath);
			ImageIO.write(bufImg, "jpg", outImgStream);
			outImgStream.flush();
			outImgStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取水印文字总长度
	 * 
	 * @param waterMarkContent
	 *            水印的文字
	 * @param g
	 * @return 水印文字总长度
	 */
	public static int getWatermarkLength(String waterMarkContent, Graphics2D g) {
		return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length());
	}

	/**
	 * 下载http文件到硬盘
	 * 
	 * @param httpUrl
	 * @param fileName
	 * @throws Exception
	 * @author lvzf 2016年11月11日
	 */
	public static void writeFileToDisk(String httpUrl, String fileName) throws Exception {
		InputStream is = HttpUtils.deGetFileInputSteam(httpUrl);
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = is.read(buffer)) != -1) {
			outStream.write(buffer, 0, len);
		}
		is.close();
		byte[] bts = outStream.toByteArray();
		File file = new File(fileName);
		FileOutputStream fops = new FileOutputStream(file);
		fops.write(bts);
		fops.flush();
		fops.close();
	}
}
